<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2017-08-30 18:10
 */

namespace api\controllers;

use api\models\ApiLoginForm;
use api\models\Fans;
use api\models\ImgUpload;
use api\models\RegistForm;
use api\models\User;
use api\models\User as ApiUser;
use common\helpers\HttpHeaderAuth;
use yii\helpers\ArrayHelper;
use yii\web\Response;
use yii;
use yii\filters\auth\QueryParamAuth;
use common\helpers\Util;
use yii\web\UploadedFile;


class UserController extends \yii\rest\ActiveController
{
    public $modelClass = "api\models\User";

    public $enableCsrfValidation=false;

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        unset($behaviors['authenticator']);

        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
            'cors'  => [
                'Origin'                           => static::allowedDomains(),
                // restrict access to
//                'Access-Control-Allow-Origin'      => ['*'],
                'Access-Control-Request-Method'    => ['POST', 'PUT', 'GET', 'OPTIONS'],
                'Access-Control-Request-Headers'   => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age'           => 86400,
                'Access-Control-Expose-Headers'    => [],
            ],
        ];
        $currentAction = Yii::$app->controller->action->id;
        //需要进行过滤的方法
        $authActions   = ['update', 'index', 'view', 'delete', 'fans-list', 'fellow-list', 'update-info'];
        if (in_array($currentAction, $authActions)) {
            $behaviors['authenticator'] = [
                'class'  => HttpHeaderAuth::className(),
                'except' => ['OPTIONS'],
            ];
        }
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
//        var_dump($behaviors['corsFilter']);
        return $behaviors;
    }


    public static function allowedDomains()
    {
        return ['*'];
    }


    public function actionLogin()
    {

        $model = new ApiLoginForm();

        $model->load(\Yii::$app->request->post(), '');

        if ($model->login()) {
            return [
                'access_token' => $model->login(),
                'expire_at'    => date('Y-m-d H:i:s', $model->expired),
                'uid'          => $model->user->id,
            ];
        } else {
            $model->validate();

            return $model; //带错误信息
        }
    }

    public function actionRegister()
    {
        $model = new RegistForm();
        $model->load(\Yii::$app->request->post(), '');
        if ($model->register()) {
            $user = new ApiLoginForm();
            $user->load(\Yii::$app->request->post(), '');
            if ($user->login()) {
                return [

                    'access_token' => $user->login(),
                    'expire_at'    => date('Y-m-d H:i:s', $model->expired),
                    'uid'          => $model->user->id,
                ];
            } else {

                Yii::$app->response->statusCode = 422;

                return ['msg' => $model->errors];
//				$user->validate();
//				return $user;
            }
        } else {
            Yii::$app->response->statusCode = 422;

            return ['msg' => $model->errors];
//			$model->validate();
//			return $model; //带错误信息
        }

    }

    public function actionUpdateInfo()
    {
        $user   = User::findIdentityByAccessToken(\Yii::$app->request->getHeaders()->get('access-token'));
        $insert = $user->avatar != '' ? true : false;
//		$user->load(Yii::$app->request->getBodyParams(),'');
        if (Util::handleImgUpload($user, 'avatar', $insert, '@avatar', []) != false) {
            Yii::$app->response->statusCode = 422;

            return ['error' => "图片上传失败"];
        }
        if ($user->save()) {
            return $user;
        } else {
            Yii::$app->response->statusCode = 422;

            return ['error' => "修改失败"];
        }
    }

    public function actionFansList($id)
    {
        return User::find()
                   ->where([
                       'in',
                       'id',
                       (new yii\db\Query())
                           ->select('ccid')
                           ->from('fans')
                           ->where(['cid' => $id])
                   ])
                   ->all();
    }

    public function actionFellowList($id)
    {
        return User::find()
                   ->where([
                       'in',
                       'id',
                       (new yii\db\Query())
                           ->select('cid')
                           ->from('fans')
                           ->where(['ccid' => $id])
                   ])
                   ->all();
    }


    public function actionProfile()
    {
        $model = User::findIdentityByAccessToken(Yii::$app->request->getHeaders()->get('access-token'));

        return $model;
    }

}
